import { createStore } from 'vuex'
import {ElMessage} from 'element-plus'
import { login} from '../api/login'

export default createStore({
  state: {
    token: localStorage.getItem('token') ? localStorage.getItem('token') : '',
    user: ''
  },
  mutations: {
    SET_TOKEN(state, val) {
      state.token = val;
      localStorage.setItem('token', val)
    },
    SET_USER(state, val) {
      state.user = val;
    },
    DEL_TOKEN(state) {
      state.token = ''
      state.user = ''
      localStorage.removeItem('token')
    },
  },
  actions: {
    login({ commit }, formdatas) {
      return new Promise((resolve, reject) => {
        login(formdatas)
            .then(res => {
              if (res.data.code == 200) {
                ElMessage.success({
                  message: '登录成功',
                  type: 'success'
                });
                commit('SET_TOKEN', res.data.data);
                commit('SET_USER', formdatas.user);
                resolve(res)
              }else{
                ElMessage.error("登录失败")
              }
            })
            .catch(error => {
              reject(error)
            })
      })
    },
  },
  modules: {
  }
})
